package com.rtx.wcs.std.handle.wcstoris;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.wcs.std.bean.po.EdiTaskCallBackLog;
import com.rtx.wcs.std.handle.ristowcs.AbsTaskDownHandle;
import com.rtx.wcs.std.service.EdiTaskCallBackLogService;
import com.rtx.wcs.std.service.LocService;
import com.rtx.wms.std.common.bean.Codelkup;
import com.rtx.wms.std.common.service.CommonService;

import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpRequest;

/**
 * 播种回传
 * @author Administrator
 *
 */
@Service("BzTaskCallBackHandle")
public class AbsBZCallBackHandle implements BzTaskCallBackHandle{

	Logger logger = LoggerFactory.getLogger(AbsTaskDownHandle.class);
	
	@Autowired
	EdiTaskCallBackLogService ediTaskCallBackLogService;
	
	@Autowired
	LocService locService;
	
	@Autowired
	CommonService commonService;
	
	ThreadPoolExecutor pool = new ThreadPoolExecutor(10, 100, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>(100));
	
	@Value("${riswms.pick.std}")
	private String riswms_pickd_std;

	@Override
	public String handleTaskCallback(String wcsCallbackRequestStr) {
		JSONObject wcsResponse = new JSONObject();
		wcsResponse.put("code", "");
		wcsResponse.put("message", "");
		wcsResponse.put("reqCode", "");
		wcsResponse.put("data", "");
		
		//生成日志
		EdiTaskCallBackLog log =  createEdiTaskCallBackLog(wcsCallbackRequestStr);

		try {
			JSONObject wcsCallbackRequest = JSON.parseObject(wcsCallbackRequestStr);
			wcsResponse.put("reqCode", wcsCallbackRequest.get("reqCode"));
			wcsResponse.put("data", wcsCallbackRequest.get("reqCode"));
			
			//校验必填字段
			check(wcsCallbackRequest);

			//处理回传逻辑
			handleCallbackBytaskCode(wcsCallbackRequest,log);
			
			wcsResponse.put("code", "0");
			wcsResponse.put("message", "success");
		} catch (Exception e) {
			logger.error("任务执行结果-异常",e);
			wcsResponse.put("code", "1");
			wcsResponse.put("message", e.getMessage());
		}finally {
			log.setEdiresponse(wcsResponse.toJSONString());
			insertLogs(log);
		}
		
		log.setEdiresponse(wcsResponse.toJSONString());
		
		return wcsResponse.toJSONString();
	}
	
	protected void insertLogs(EdiTaskCallBackLog log) {
		try {
			pool.execute(()->{
				ediTaskCallBackLogService.insertLog("ris_edi", log);
	        });
			
		} catch (Exception e) {
			logger.error("",e);
		}
	};
	
	/**
	 * 生成日志实体类
	 * @return
	 */
	protected EdiTaskCallBackLog createEdiTaskCallBackLog(String wcsRequest) {
		EdiTaskCallBackLog log = new EdiTaskCallBackLog();
		log.setApiname("WCS->WMS播种回传");
		log.setWcsrequest(wcsRequest);
		log.setWcsrequesturl("/v1/edi/bz/callback");
		log.setAdddate(LocalDateTime.now());

		JSONObject request = JSON.parseObject(wcsRequest);
		log.setWhseid(request.getString("whseid"));
		log.setTagcode(request.getString("tagCode"));
		
		return log;
	};
	
	
	//{"controllerCode":"group01","tagCode":"格口号","display":"","eventCode":"LIGHT_OFF","status":0}
	protected void check(JSONObject request ) {
		Assert.hasLength(request.getString("whseid"), "whseid为必填字段");
		Assert.hasLength(request.getString("tagCode"), "tagCode为必填字段");
		Assert.hasLength(request.getString("display"), "display为必填字段");
	}
	
	//	接口根据回传的状态执行以下逻辑：
	//	判断状态是否为0
	//	是，根据电子标签、数量，调用功能【标准拣货】逻辑，执行拣货处理
	//	否，线下人工处理。
	protected void handleCallbackBytaskCode(JSONObject request,EdiTaskCallBackLog log) {
		String whseid = request.getString("whseid");
		String tagCode = request.getString("tagCode");
		String controllerCode = request.getString("controllerCode");
		String status = request.getString("status");
		String qty = request.getString("display");
		
		LambdaQueryWrapper<Codelkup> cqw = Wrappers.lambdaQuery();
		cqw.eq(Codelkup::getListname, "RTXSOWPOSITION");
		cqw.eq(Codelkup::getCode, tagCode);
		cqw.eq(Codelkup::getUdf1, controllerCode);
		List<Codelkup> configList = commonService.selectCodelkupByWrapper(whseid, cqw);
		
		
		if("0".equals(status)) {
			JSONObject ediRequest = new JSONObject();
			ediRequest.put("whseid", whseid);
			ediRequest.put("sowdevice", controllerCode);//设备号
			ediRequest.put("seqno", configList.get(0).getUdf2());//格口号
			ediRequest.put("qty", qty);//数量
			
			//调用riswms标准拣货
			callWMSAPI(ediRequest,log);
		}
		
	}
	
	//调用riswms标准拣货
	protected String callWMSAPI(JSONObject request,EdiTaskCallBackLog log) {
		String uuid = UUID.randomUUID().toString();
		String requestStr = request.toJSONString();
		log.setEdirequesturl(requestStr);
		log.setEdirequest(requestStr);
		logger.info("uid-{}-tagcode-{}-url-{}-任务执行结果-调用标准移动-请求报文-{}",uuid,request.getString("tagCode"),riswms_pickd_std,requestStr);
		String	result = HttpRequest
				.post(riswms_pickd_std)
				.body(request.toJSONString())
				.timeout(30000)
				.execute()
				.body();
		logger.info("uid-{}-tagcode-{}-任务执行结果-调用标准移动-响应报文-{}",uuid,request.getString("tagCode"),riswms_pickd_std,result);
		log.setRiswmsresponse(result);
		JSONObject res = JSON.parseObject(result);
		
		if(!"200".equals(res.getString("returnCode"))) {
			throw new RuntimeException(result);
		}
		return result;
	};
}
